using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using ResxHelper.Logic;
using ResxHelper.Logic.Converter;
using ResxHelper.Logic.Readers;
using ResxHelper.Object;
using System.IO;

namespace ResxHelper.Forms
{
    public partial class FrmMain : Form
    {
        public event FileChangedEventHandler FileChanged;
        private ResourceFile _loadedResx;

        #region -- Initilizers --
        public FrmMain()
        {
            InitializeComponent();
            InitializeControls();
            FileChanged += OnFileChanged;
        }        
        private void LoadGridData(ResourceFile resourceFile)
        {
            if (resourceFile == null || resourceFile.Entries == null || resourceFile.Entries.Count < 1) return;
            var entries = resourceFile.Entries;
            var listEntries = entries.Select(entry => entry.Value).ToList();
            var list = new BindingList<ResourceFileEntry>(listEntries);
            dgPreview.DataSource = list;
        }
        private void InitializeGrid()
        {
            dgPreview.AutoGenerateColumns = false;
            dgPreview.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
            dgPreview.RowHeadersVisible = false;
            var cell = new DataGridViewTextBoxCell();
            var key = new DataGridViewTextBoxColumn
            {
                CellTemplate = cell,
                Name = "Key",
                HeaderText = "Key",
                DataPropertyName = "Key"
            };
            var value = new DataGridViewTextBoxColumn
            {
                CellTemplate = cell,
                Name = "Value",
                HeaderText = "Value",
                DataPropertyName = "Value"
            };
            var comment = new DataGridViewTextBoxColumn
            {
                CellTemplate = cell,
                Name = "Comment",
                HeaderText = "Comment",
                DataPropertyName = "Comment"
            };
            dgPreview.Columns.AddRange(new DataGridViewColumn[] { key, value, comment });
        }
        private void InitializeControls()
        {
            InitializeGrid();
        }
        #endregion

        #region -- Menus --
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var diag = new OpenFileDialog { Filter = ApplicationConstants.SupportedTypesFilter };
            var result = diag.ShowDialog();
            if (result == DialogResult.OK)
            {
                var type = ResourceFile.ResourceType(diag.FileName);
                var reader = ResourceFileReaderFactory.GetReader(diag.FileName, type);

                LoadResourceFileToMemory(reader.Read());
                LoadGridData(_loadedResx);
            }

            menuActions.Enabled = true;
        }
        private void exportSelectedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result;
            var savePath = DialogHelper.GetSaveFileLocation(ApplicationConstants.SaveTypesAllFilter, out result);
            if (result != DialogResult.OK) return;

            FileHelper.SaveAs(_loadedResx, savePath);

            statusActionUpdate.Text = string.Format("Saved {0}", Path.GetFileName(savePath));
        }
        private void exportAllRelatedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!IsFileLoaded()) return;

            // get options
            var optionPrompt = new FrmExportMultipleOptions();
            optionPrompt.ShowDialog();
            var option = optionPrompt.Option;
            var format = optionPrompt.Format;

            optionPrompt.Close();
            optionPrompt.Dispose();

            var allFiles = ResourceFile.GetAllResourceFiles(_loadedResx.FilePath);

            // Do the deed
            var saveDirectory = DialogHelper.GetSaveDirectory();
            FileHelper.Export(allFiles, saveDirectory, format, option);

            statusActionUpdate.Text = string.Format("Saved files to {0}", saveDirectory);
        }
        private void showMissingKeysToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (!IsFileLoaded()) return;

            var result = Core.GetMissingKeysFromInvariant(_loadedResx.FilePath);
            var resultDisplay = new FrmMissingWords(result);
            resultDisplay.ShowDialog();
        }
        private void importOpen_Click(object sender, EventArgs e)
        {
            var filePath = DialogHelper.PromptForFile(ApplicationConstants.SupportedTypesFilter);
            var type = ResourceFile.ResourceType(filePath);

            var reader = ResourceFileReaderFactory.GetReader(filePath, type);
            var resourceFile = reader.Read();

            LoadResourceFileToMemory(resourceFile);
            LoadGridData(_loadedResx);
        }
        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var dialog = new SaveFileDialog
            {
                AddExtension = true,
                Filter = ApplicationConstants.SaveTypesAllFilter,
                FileName = _loadedResx.GetFileNameWithoutExtension()
            };

            if (dialog.ShowDialog() != DialogResult.OK) return;

            var savePath = dialog.FileName;

            FileHelper.SaveAs(_loadedResx, savePath);
            statusActionUpdate.Text = string.Format("Saved to {0}", savePath);
        }
        private void mergeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var mergeForm = new FrmMerge();
            mergeForm.ShowDialog();
        }
        #endregion

        private void LoadResourceFileToMemory(ResourceFile file)
        {
            _loadedResx = file;
            OnFileChanged(this, new ResourceFileChangedEventArgs(file));
        }
        private bool IsFileLoaded()
        {
            if (_loadedResx == null)
            {
                MessageBox.Show("Please load a .resx file first");
                return false;
            }

            return true;
        }
        protected virtual void OnFileChanged(object sender, ResourceFileChangedEventArgs e)
        {
            if (FileChanged == null || e.File == null) return;
            var fileExt = Path.GetExtension(e.File.FilePath);

            // enable actions
            menuActions.Enabled = _loadedResx != null;
            saveAsToolStripMenuItem.Enabled = _loadedResx != null;
            exportToolStripMenuItem.Enabled = _loadedResx != null;

            // disable export if loaded file came from csv
            exportToolStripMenuItem.Enabled = fileExt != ".csv";

            // update status bar
            statusLoadedFile.Text = _loadedResx.FileName;
            statusActionUpdate.Text = "Ready";
        }

        private void bulkResourceToExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var bulkForm = new FrmDropConvert();
            Hide();
            bulkForm.ShowDialog();
            Show();
        }
    }

    public delegate void FileChangedEventHandler(object sender, ResourceFileChangedEventArgs e);
}
